package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.Owner;
import com.hanserwei.community.entity.po.ParkingSpace;
import com.hanserwei.community.entity.request.parking.ParkingSpaceQueryRequest;
import com.hanserwei.community.entity.request.parking.ParkingSpaceSaveRequest;
import com.hanserwei.community.entity.vo.OwnerBriefVO;
import com.hanserwei.community.entity.vo.ParkingSpaceVO;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.mapper.ParkingSpaceMapper;
import com.hanserwei.community.service.OwnerService;
import com.hanserwei.community.service.ParkingSpaceService;
import com.hanserwei.community.uitils.ThrowUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class ParkingSpaceServiceImpl extends ServiceImpl<ParkingSpaceMapper, ParkingSpace> implements ParkingSpaceService {

    private final OwnerService ownerService;

    @Override
    public Page<ParkingSpaceVO> pageParkingSpaces(ParkingSpaceQueryRequest request) {
        Page<ParkingSpace> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<ParkingSpace> queryWrapper = buildQueryWrapper(request);
        Page<ParkingSpace> parkingPage = page(page, queryWrapper);
        List<ParkingSpaceVO> voList = convertToVOList(parkingPage.getRecords());
        Page<ParkingSpaceVO> voPage = new Page<>(parkingPage.getCurrent(), parkingPage.getSize(), parkingPage.getTotal());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public ParkingSpaceVO getParkingSpaceDetail(Integer id) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "车位ID参数错误！");
        ParkingSpace parkingSpace = getById(id);
        ThrowUtils.throwIf(parkingSpace == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "车位不存在！");
        List<ParkingSpaceVO> list = convertToVOList(Collections.singletonList(parkingSpace));
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public boolean createParkingSpace(ParkingSpaceSaveRequest request) {
        validateSaveRequest(null, request);
        ParkingSpace parkingSpace = new ParkingSpace();
        BeanUtils.copyProperties(request, parkingSpace);
        boolean result = save(parkingSpace);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "新增失败！");
        return true;
    }

    @Override
    public boolean updateParkingSpace(Integer id, ParkingSpaceSaveRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "车位ID参数错误！");
        validateSaveRequest(id, request);
        ParkingSpace parkingSpace = getById(id);
        ThrowUtils.throwIf(parkingSpace == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "车位不存在！");
        BeanUtils.copyProperties(request, parkingSpace);
        parkingSpace.setId(id);
        boolean result = updateById(parkingSpace);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新失败！");
        return true;
    }

    @Override
    public QueryWrapper<ParkingSpace> buildQueryWrapper(ParkingSpaceQueryRequest request) {
        QueryWrapper<ParkingSpace> wrapper = new QueryWrapper<>();
        if (request == null) {
            return wrapper;
        }
        wrapper.eq(request.getId() != null && request.getId() > 0, "id", request.getId());
        wrapper.like(StringUtils.hasText(request.getNumbers()), "numbers", request.getNumbers());
        wrapper.eq(request.getStatus() != null, "status", request.getStatus());
        wrapper.eq(request.getOwnerId() != null && request.getOwnerId() > 0, "owner_id", request.getOwnerId());
        if (StringUtils.hasText(request.getOwnerName())) {
            List<Integer> ownerIds = ownerService.lambdaQuery()
                    .like(Owner::getUserName, request.getOwnerName())
                    .select(Owner::getId)
                    .list()
                    .stream()
                    .map(Owner::getId)
                    .distinct()
                    .toList();
            if (ownerIds.isEmpty()) {
                wrapper.apply("1 = 0");
            } else {
                wrapper.in("owner_id", ownerIds);
            }
        }
        wrapper.orderBy(StringUtils.hasText(request.getSortField()), !"descend".equalsIgnoreCase(request.getSortOrder()), request.getSortField());
        return wrapper;
    }

    private void validateSaveRequest(Integer id, ParkingSpaceSaveRequest request) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(!StringUtils.hasText(request.getNumbers()), ResponseCodeEnum.INVALID_PARAMETER, "车位编号不能为空！");
        Long duplicate = lambdaQuery()
                .eq(ParkingSpace::getNumbers, request.getNumbers())
                .ne(id != null && id > 0, ParkingSpace::getId, id)
                .count();
        ThrowUtils.throwIf(duplicate != null && duplicate > 0, ResponseCodeEnum.INVALID_PARAMETER, "车位编号已存在！");
        if (request.getOwnerId() != null && request.getOwnerId() > 0) {
            Owner owner = ownerService.getById(request.getOwnerId());
            ThrowUtils.throwIf(owner == null, ResponseCodeEnum.INVALID_PARAMETER, "关联业主不存在！");
        }
    }

    private List<ParkingSpaceVO> convertToVOList(List<ParkingSpace> parkingSpaces) {
        if (CollectionUtils.isEmpty(parkingSpaces)) {
            return Collections.emptyList();
        }
        Set<Integer> ownerIds = parkingSpaces.stream()
                .map(ParkingSpace::getOwnerId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Integer, Owner> ownerMap = ownerIds.isEmpty() ? Collections.emptyMap() : ownerService.listByIds(ownerIds).stream()
                .collect(Collectors.toMap(Owner::getId, owner -> owner));

        return parkingSpaces.stream().map(space -> {
            ParkingSpaceVO vo = new ParkingSpaceVO();
            BeanUtils.copyProperties(space, vo);
            if (space.getOwnerId() != null) {
                Owner owner = ownerMap.get(space.getOwnerId());
                vo.setOwnerId(space.getOwnerId());
                if (owner != null) {
                    vo.setOwner(toOwnerBrief(owner));
                }
            }
            return vo;
        }).toList();
    }

    private OwnerBriefVO toOwnerBrief(Owner owner) {
        if (owner == null) {
            return null;
        }
        return OwnerBriefVO.builder()
                .id(owner.getId())
                .name(owner.getUserName())
                .tel(owner.getTel())
                .houseId(owner.getHouseId())
                .build();
    }
}
